﻿
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Data;
using WidgetsDesign.API.DataBase;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;


// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WidgetsDesign.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class zyxk_fireController : ControllerBase
    {
        private readonly Izyxk_fireRepository _fireRepository;
        private readonly IMapper _Mapper;
        private readonly AppDbContext _context;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public zyxk_fireController(IWebHostEnvironment webHostEnvironment, Izyxk_fireRepository fireRepository, IMapper mapper, AppDbContext context)
        {
            _fireRepository = fireRepository;
            _Mapper = mapper;
            _context = context;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// word转pdf
        /// </summary>
        /// <param name="fireToPdf"></param>
        /// <returns></returns>



        [HttpPost]
        public async Task<IActionResult> fireToPdf(string Id)
        {
            var fire = await _context.zyxk_fire.FirstOrDefaultAsync(co => co.Id == Id);
            var saveName = @"Pdf\动火作业许可证" + Id + ".pdf";

            string web_path = _webHostEnvironment.WebRootPath;
            string folderPath = Path.Combine("wwwroot");

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string path = Path.Combine(folderPath, saveName);
            string inpath = Path.Combine(folderPath, @"wordmodel\动火作业许可证.docx");
            string inputFilePath = inpath;// 替换为你的Word文档路径  
            string outputFilePath = path;

            if (fire == null)
            {
                // 如果没有找到记录，返回错误信息  
                return Ok(new { code = 200, ret = false, data = "", message = "未找到对应的动火作业许可证记录" });
            }
            else
            {
                string last = _fireRepository.zyxk_fireTopdf(inputFilePath, outputFilePath, fire);
                return Ok(new { code = 200, ret = true, data = saveName, message = "创建成功" + outputFilePath });

            }

        }
        /// <summary>
        /// 增加基础信息
        /// </summary>
        /// <param name="fire"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Createfire([FromBody] zyxk_fireModel fire)
        {
            if (String.IsNullOrEmpty(fire.Id))
            {
                fire.Id = Guid.NewGuid().ToString();
                fire.state = "1";
                _fireRepository.Createfire(fire);
                await _fireRepository.SaveAsync();
                return Ok(new { code = 200, ret = true, data = fire, message = "创建成功" });
            }
            else
            {
                var query = from d in _context.zyxk_fire
                            where d.Id == fire.Id
                            select d;
                var item = await query.FirstOrDefaultAsync();
                if (item != null)
                {
                    item.applicantCompany = fire.applicantCompany;
                    item.applyTime = fire.applyTime;
                    item.CancelorClose = fire.CancelorClose;
                    item.endtime = fire.endtime;
                    item.firetype = fire.firetype;
                    item.gas = fire.gas;
                    item.guardian = fire.guardian;
                    item.homeworkAreaManagementUnit = fire.homeworkAreaManagementUnit;
                    item.Id = fire.Id;
                    item.isplan = fire.isplan;
                    item.jobContent = fire.jobContent;
                    item.jobContent1 = fire.jobContent1;
                    item.jobMonitoring = fire.jobMonitoring;
                    item.location = fire.location;
                    item.noNumber = fire.noNumber;
                    item.operatorApplication = fire.operatorApplication;
                    item.operatorman = fire.operatorman;
                    item.othernumber = fire.othernumber;
                    item.oxygendensity = fire.oxygendensity;
                    item.preparedman = fire.preparedman;
                    item.proposer = fire.proposer;
                    item.ratify = fire.ratify;
                    item.risk = fire.risk;
                    item.signatureman = fire.signatureman;
                    item.stakeholder = fire.stakeholder;
                    item.starttime = fire.starttime;
                    item.state = fire.state;
                    item.territorySupervisor = fire.territorySupervisor;
                    item.testask = fire.testask;
                    item.testman = fire.testman;
                    item.toxicgas = fire.toxicgas;
                    item.workLocation = fire.workLocation;
                    if (!string.IsNullOrEmpty(fire.safe))
                    {
                        item.safe = fire.safe;
                    }
                    if (!string.IsNullOrEmpty(fire.preparedman))
                    {
                        item.preparedman = fire.preparedman;
                    }
                    if (!string.IsNullOrEmpty(fire.scheduleId))
                    {
                        item.scheduleId = fire.scheduleId;
                    }
                    if (!string.IsNullOrEmpty(fire.scheduleContent))
                    {
                        item.scheduleContent = fire.scheduleContent;
                    }
                }
                await _context.SaveChangesAsync();
                return Ok(new { ret = true, data = item, code = 200 });
            }
        }
        /// <summary>
        /// 增加风险
        /// </summary>
        /// <param name="fire"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreatefireRisk([FromBody] zyxk_fireModel fire)
        {
            _fireRepository.CreatefireRisk(fire);
            fire.state = "2";
            await _fireRepository.SaveAsync(); return Ok(new { code = 200, data = "", ret = true });
        }
        /// <summary>
        /// 增加签字
        /// </summary>
        /// <param name="fire"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreatefireSign([FromBody] zyxk_fireModel fire)
        {
            _fireRepository.CreatefireSign(fire);
            fire.state = "3";
            await _fireRepository.SaveAsync(); return Ok(new { code = 200, data = "", ret = true });
        }
        /// <summary>
        /// 创建表单关闭状态
        /// </summary>
        /// <param name="fire"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreatefireClose([FromBody] zyxk_fireModel fire)
        {
            var query = from d in _context.zyxk_fire
                        where d.Id == fire.Id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            if (item != null && !String.IsNullOrEmpty(fire.CancelorClose))
            {
                zyxk_Model.CancelorClose safeDataList = JsonConvert.DeserializeObject<zyxk_Model.CancelorClose>(fire.CancelorClose);
                if (safeDataList.endtype == "1")
                {
                    item.state = "7";
                }
                if (safeDataList.endtype == "2")
                {
                    item.state = "6";
                }
                if (safeDataList.endtype == "3")
                {
                    item.state = "5";
                }
                item.CancelorClose = fire.CancelorClose;
                await _context.SaveChangesAsync();
            }
            return Ok(new { ret = true, data = item, code = 200 });
        }
       
        /// <summary>
        /// 查询列表根据时间
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryfireList([FromQuery] int pageIndex, int pageSize, DateTime? startTime, DateTime? endTime)
        {

            var query = _context.zyxk_fire.Select(h => new zyxk_Model.TableData
            {
                Id = h.Id,
                ApplyTime = h.applyTime,
                WorkLocation = h.workLocation,
                EndTime = h.endtime,
                State = h.state,
                JobContent = h.jobContent,
                ApplicantCompany = h.applicantCompany,
                Proposer = h.proposer
            });
            if (startTime.HasValue)
            {
                query = query.Where(h => h.ApplyTime >= startTime);
            }

            if (endTime.HasValue)
            {
                query = query.Where(h => h.ApplyTime <= endTime);
            }
            var total = await query.CountAsync();
            query = query.OrderByDescending(h => h.ApplyTime);

            query = query.Skip(pageSize * (pageIndex - 1))
                     .Take(pageSize);

            var list = await query.ToListAsync();
            for (int i = 0; i < list.Count; i++)
            {
                if (int.Parse(list[i].State) <= 4)
                {
                    if (list[i].EndTime <= DateTime.Now)
                    {
                        list[i].State = "7";
                    }
                }
            }
            return Ok(new { ret = true, data = list, code = 200, total });
        }
        /// <summary>
        /// 查询根据id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryfireById([FromQuery] string Id)
        {
            var query = from d in _context.zyxk_fire
                        where d.Id == Id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            return Ok(new { ret = true, data = item, code = 200 });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Deletefire([FromQuery] string Id)
        {
            var query = from d in _context.zyxk_fire where d.Id == Id select d;
            _context.zyxk_fire.RemoveRange(query);
            _context.SaveChanges();
            return Ok(new { ret = true, data = new { }, code = 200 });
        }
        /// <summary>
        /// 选择附表
        /// </summary>
        /// <param name="fire"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreatefireSchedule([FromBody] zyxk_fireModel fire)
        {
            var query = from d in _context.zyxk_fire
                        where d.Id == fire.Id
                        select d;
            var item = await query.FirstOrDefaultAsync();
            if (item != null)
            {
                //判断当前传入的ScheduleId不为空
                if (!String.IsNullOrEmpty(fire.scheduleId))
                {   //判断当前ScheduleId和数据库ScheduleId是否一致
                    if (item.scheduleId != fire.scheduleId)
                    {
                        item.scheduleId = fire.scheduleId;
                        item.scheduleContent = fire.scheduleContent;
                    }
                }
                if (String.IsNullOrEmpty(fire.scheduleId) && !String.IsNullOrEmpty(fire.scheduleContent))
                {
                    item.scheduleContent = fire.scheduleContent;
                }
            }
            await _context.SaveChangesAsync();
            return Ok(new { ret = true, data = item, code = 200 });
        }
    }
}
